<?php

namespace App\Admin\Controllers\Manger;

use App\Admin\Validate\Manger\Manger;
use Illuminate\Http\Request;

use App\Http\Controllers\Controller;
use App\Models\Admin\AdminUser;
use App\Models\Company;
use App\Models\Manger\Manger as ModelsMangerManger;
use App\Models\Manger\Mangerrule;
use App\Services\Manger\MangerAccount;
use Illuminate\Support\Facades\Redis;

class MangerController extends Controller
{

    /**
     * 新增
     */
    public function dopostadd(Request $request)
    {
        $req_data = $request->only(['cpid', 'username', 'mobile', 'cpd_user_id']);

        $Validate = new Manger;
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }
        $commany_info = Company::where([['id', $req_data['cpid']]])->first();
        if (!$commany_info) {
            return response()->json(['code' => '001', 'msg' => '账套信息不存在']);
        }
        $is_has_manger = ModelsMangerManger::where([['cpid', $req_data['cpid']], ['status', 1], ['utype', 1]])->count();

        if ($is_has_manger > 0) {
            return response()->json(['code' => '001', 'msg' => '该账套已存在管理员，请勿重复添加']);
        }
        $isexist = ModelsMangerManger::where([['cpid', $req_data['cpid']], ['username', $req_data['username']]])
            ->orWhere([['cpid', $req_data['cpid']], ['mobile', $req_data['mobile']]])
            // ->orWhere([['realname', $req_data['realname']], ['cpid', $req_data['cpid']]])
            ->first();

        if ($isexist) {
            return response()->json(['code' => '001', 'msg' => '账套名、用户名、手机号不允许重复']);
        }

        //判断账套信息是否包含超管信息

        $isexist = AdminUser::where([['username', $req_data['username']]])->first();

        if ($isexist) {
            return response()->json(['code' => '001', 'msg' => '管理员信息不可与超管信息相同']);
        }

        $data = [
            'cpid' => $req_data['cpid'],
            'username' => $req_data['username'],
            'mobile' => $req_data['mobile'],
            'utype' => 1,
            'utypes' => 1,
            // 'cpd_user_id' => $req_data['cpd_user_id'],
            'update_at' => time()
        ];
        $data['password'] = MD5(MD5('huakun_' . env('MANGER_DEF_PWD')));
        $data['create_at'] = time();
        $manger_id = ModelsMangerManger::create($data)->id;
        //设置默认权限
        MangerAccount::setMangerRule($manger_id, 1);

        return response()->json(['code' => '000', 'msg' => '新增成功']);
    }

    /**
     * 编辑
     */
    public function dopostedit(Request $request)
    {
        $id = $request->id ?? 0;
        $mobile = $request->mobile ?? '';
        $cpd_user_id = intval($request->cpd_user_id);
        $info = ModelsMangerManger::where([['id', $id], ['status', 1]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        if ($mobile == '') {
            return response()->json(['code' => '001', 'msg' => '手机号不能为空']);
        }
        // if ($cpd_user_id <= 0) {
        //     return response()->json(['code' => '001', 'msg' => '钉钉用户未选择']);
        // }

        $isexist = ModelsMangerManger::where([['id', '<>', $id], ['cpid', '<>', $info['cpid']], ['mobile', $mobile]])->first();
        if ($isexist) {
            return response()->json(['code' => '001', 'msg' => '手机号不允许重复']);
        }
        ModelsMangerManger::where([['id', $id]])->update(['update_at' => time(),
         'mobile' => $mobile, 
        //  'cpd_user_id' => $cpd_user_id
        ]);

        return response()->json(['code' => '000', 'msg' => '编辑成功']);
    }

    /**
     * 获取列表
     */
    public function getlist(Request $request)
    {
        $limit = $request->limit ?? 10;
        $query = ModelsMangerManger::
        // with('cpduserinfo')->
        where(['utypes' => 1, 'pid' => 0])->orderBy('create_at', 'desc');
        $username = $request->username;
        if ($username != '') {
            $query->where('username', 'like', '%' . $username . '%');
        }

        $status = $request->status ?? 0;
        if (in_array($status, [1, 2])) {
            $query->where('status', $status);
        }
        $list = $query->select(['id', 'cpid', 'pid', 'username', 'mobile', 'status', 'cpd_user_id'])->paginate($limit)->toArray();
        // print_r($list);exit;
        foreach ($list['data'] as &$val) {
            $commany_info = Company::
            // with('cpdinfo')->
            where([['id', $val['cpid']]])->first();
            $val['company_name'] = $commany_info->company_name;
            $val['other_title'] = $commany_info->other_title;
            // $val['cpdinfo'] = $commany_info->cpdinfo;
        }

        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => paginateDataToArray($list)]);
    }

    /**
     * 冻结
     */
    public function changestatus(Request $request)
    {
        $id = $request->id ?? 0;
        $info = ModelsMangerManger::where([['id', $id]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $status = 2;
        ModelsMangerManger::where([['id', $id]])->update(['status' => $status, 'update_at' => time()]);

        //冻结需删除管理员以及子账号登录状态

        MangerAccount::clearTokenKey($id);


        $mangerlist=ModelsMangerManger::where([['cpid', $info->cpid]])->get()->toArray();
        foreach($mangerlist as $val){
            ModelsMangerManger::where([['cpid', $info->cpid],['id',$val['id']]])->update(['status'=>2,'update_at'=>time()]);
            MangerAccount::cleartokenkey($val['id']);
        }


        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 重置密码
     */
    public function resetpassword(Request $request)
    {
        //重置后需重置账号登陆状态

        $id = $request->id ?? 0;
        $info = ModelsMangerManger::where([['id', $id]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $password = MD5(MD5('huakun_' . env('MANGER_DEF_PWD')));
        ModelsMangerManger::where([['id', $id]])->update(['password' => $password, 'update_at' => time()]);

        //重置后需重置账号登陆状态
        MangerAccount::cleartokenkey($id);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 获取权限
     */

    public function getruleinfo(Request $request)
    {
        //获取菜单列表以及管理员已设置的权限
        $id = $request->id ?? 0;
        $info = ModelsMangerManger::where([['id', $id]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $rule_info = Mangerrule::where(['mid' => $id])->first();
        $ruleinfo = json_decode($rule_info->ruleinfo, true);
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $ruleinfo]);
    }
    /**
     * 设置权限
     */
    public function dopostrule(Request $request)
    {

        //设置权限后，需要对比用户现有权限
        $id = $request->id ?? 0;
        $ruleinfo = is_array($request->ruleinfo) ? $request->ruleinfo : (is_array(json_decode($request->ruleinfo, true)) ? json_decode($request->ruleinfo, true) : []);
        $info = ModelsMangerManger::where([['id', $id]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        if (count($ruleinfo) <= 0) {
            return response()->json(['code' => '001', 'msg' => '权限菜单信息有误']);
        }
        $rule_info = json_encode($ruleinfo);
        Mangerrule::where(['mid' => $id])->update(['ruleinfo' => $rule_info]);
        //重置用户现有权限
        // Redis::set('manger_user_menulist_' . $id, $rule_info);
        $utype = 1;
        Redis::set('manger_user_menulist_' . $id . '_' . $utype, $rule_info);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }
}
